package com.joeyzh.imagepicker.handwritingboard;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.joey.base.util.DataFormatUtils;
import com.joeyzh.imagepicker.R;
import com.joeyzh.imagepicker.utils.CompressBitmapUtils;
import com.joeyzh.imagepicker.utils.ImagePickerManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class HandwritingBoardActivity extends AppCompatActivity {

    public static final String FORMATTER_DATE_AND_TIME = "yyyyMMddhhmmss";
    /**
     * 压缩的宽高
     */
    private static int compressHeight = 800;
    private static int compressWidth = 480;
    private String creatTime;
    /**
     * 写字板图片存储路径
     */
    private static String SignaturePath;

    public static void setCompressHeight(int compressHeight) {
        HandwritingBoardActivity.compressHeight = compressHeight;
    }

    public static void setCompressWidth(int compressWidth) {
        HandwritingBoardActivity.compressWidth = compressWidth;
    }

    public static void deleteAllFiles() {
        deleteAllFiles(new File(SignaturePath));
    }

    /**
     * 删除文件
     *
     * @param root
     */
    public static void deleteAllFiles(File root) {
        File files[] = root.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) { // 判断是否为文件夹
                    deleteAllFiles(f);
                    try {
                        f.delete();
                    } catch (Exception e) {
                    }
                } else {
                    if (f.exists()) {
                        // 判断是否存在
                        deleteAllFiles(f);
                        try {
                            f.delete();
                        } catch (Exception e) {
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pictools_activity_handwriting_board);
        gainPermission();
        gainCurrenTime();
        initView();
    }

    /**
     * 判断是否开启权限
     */
    private void gainPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ContextCompat.checkSelfPermission(HandwritingBoardActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(HandwritingBoardActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 4);
            } else {
                Toast.makeText(this, "已开启权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 获取系统时间
     */
    private String gainCurrenTime() {
        creatTime = DataFormatUtils.getTime(System.currentTimeMillis(), FORMATTER_DATE_AND_TIME);
        return creatTime;
    }

    /**
     * 初始化布局
     */
    private void initView() {
        final Button mClearButton = (Button) findViewById(R.id.clear_button);
        final Button mSaveButton = (Button) findViewById(R.id.save_button);
        final SignatureView mSignaturePad = (SignatureView) findViewById(R.id.signature_pad);
        //设置写字板路径
        SignaturePath = getIntent().getStringExtra("SignaturePath");

        if (null == SignaturePath || SignaturePath.isEmpty()){
            SignaturePath = ImagePickerManager.getSignaturePath();
        }
        mSignaturePad.setOnSignedListener(new SignatureView.OnSignedListener() {
            @Override
            public void onSigned() {
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
            }

            @Override
            public void onClear() {
                mSaveButton.setEnabled(false);
                mClearButton.setEnabled(false);
            }
        });

        mClearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清空
                mSignaturePad.clear();
            }
        });


        mSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                //压缩图片
                Bitmap bitmap = CompressBitmapUtils.compressScale(signatureBitmap, compressHeight, compressWidth);
                Intent intent = addSignatureToGallery(bitmap);
                //保存
                if (null == intent) {
                    Toast.makeText(HandwritingBoardActivity.this, "保存失败！请检查图片路径或格式！", Toast.LENGTH_SHORT).show();
                } else {
                    //回调
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    /**
     * 获取文件存储目录
     *
     * @param albumName
     * @return
     */
    public File getAlbumStorageDir(String albumName) {
        File file = new File(Environment.getExternalStorageDirectory(), albumName);
        if (!file.mkdirs()) {
            Log.e("SignaturePad", "Directory not created");
        }
        return file;
    }

    /**
     * 保存图片
     *
     * @param signature
     * @param path
     * @return
     */
    public Intent addSignatureToGallery(Bitmap signature, String path) {
        final File photo = new File(path);
        return addSignatureToGallery(signature, photo);
    }

    public Intent addSignatureToGallery(Bitmap signature) {
        //存到本地项目下
        final File photo = new File(SignaturePath, gainCurrenTime() + ".jpg");
        return addSignatureToGallery(signature, photo);
    }

    public Intent addSignatureToGallery(Bitmap signature, File photo) {
        Intent mediaScanIntent = null;
        try {
            saveBitmapToJPG(signature, photo);
            mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(photo);
            mediaScanIntent.setData(contentUri);
        } catch (IOException e) {
            e.printStackTrace();
            mediaScanIntent = null;
        }
        return mediaScanIntent;
    }

    /**
     * 保存图片
     *
     * @param bitmap
     * @param photo
     * @throws IOException
     */
    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 4:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "已打开权限！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "请打开权限！", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        /**
         * 设置为横屏
         */
        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
        super.onResume();
    }
}
